package com.example.service;


import com.example.entity.Book;
import com.example.entity.Category;
import com.example.exception.CustomerException;
import com.example.mapper.CategoryMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryService {
    @Autowired
    private BookService bookService;
    @Autowired
    private CategoryMapper categoryMapper;
    public List<Category> selectAll(Category category){
        return categoryMapper.selectAll(category);
    }

    public PageInfo<Category> selectPage(Integer pageNum, Integer pageSize,Category category) {
        PageHelper.startPage(pageNum,pageSize);
        List<Category> list = categoryMapper.selectAll(category);
        return PageInfo.of(list);

    }

    public void add(Category category) {
        categoryMapper.insert(category);
    }

    public void update(Category category) {
        categoryMapper.updateById(category);
    }

    public void deleteById(Integer id) {
        Book book = bookService.selectByCategoryId(id);
        if (book==null){
            categoryMapper.deleteById(id);
        }else {
            throw new CustomerException("该分类下存在书籍，无法删除");
        }
    }


    @Transactional
    public void deleteBatch(List<Integer> idList) {
        for (Integer id : idList) {
//            categoryMapper.deleteById(id);
            this.deleteById(id);
        }
    }
}
